package me.cxlr.qinlauncher2.view.settings;

import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.appcompat.app.AlertDialog;
import androidx.preference.DropDownPreference;
import androidx.preference.PreferenceCategory;
import androidx.preference.PreferenceFragmentCompat;

import java.util.List;

import me.cxlr.qinlauncher2.R;
import me.cxlr.qinlauncher2.manager.IconManager;
import me.cxlr.qinlauncher2.manager.SoftwareManager;
import me.cxlr.qinlauncher2.dao.AppDao;
import me.cxlr.qinlauncher2.model.App;
import me.cxlr.qinlauncher2.util.ThemeUtil;

/**
 * @author 酷安用户:山轮纸
 */
public class ShowHiddenAppSettingsFragment extends PreferenceFragmentCompat {
    private AppDao appDao;

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.preferences_show_hidden_app_settings, rootKey);
        appDao = new AppDao();

        PreferenceCategory preferenceCategory = getPreferenceManager().findPreference("ps_show_hidden_app");
        List<App> hiddenAppList = appDao.findHiddenApp();
        if (hiddenAppList.size() > 0) {
            for (App entity : hiddenAppList) {
                DropDownPreference dropDownPreference = new DropDownPreference(requireContext());
                dropDownPreference.setTitle(entity.getLabel());
                dropDownPreference.setSummary("");

                Drawable icon = IconManager.getInstance().getApplicationIcon(entity.getPackageName(), entity.getClazzName());
                dropDownPreference.setIcon(icon);

                dropDownPreference.setOnPreferenceClickListener(preference -> {
                    removeHiddenList(dropDownPreference, entity);
                    return false;
                });

                assert preferenceCategory != null;
                preferenceCategory.addItemFromInflater(dropDownPreference);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        ThemeUtil.initTheme();
    }

    private void removeHiddenList(DropDownPreference dropDownPreference, App app) {
        AlertDialog alertDialog = new AlertDialog.Builder(requireContext())
                .setTitle("恢复到应用抽屉")
                .setMessage("取消隐藏后会在应用抽屉中显示")
                .setPositiveButton("是", (dialog, which) -> {
                    app.getAppDrawer().setHidden(false);
                    appDao.updateApp(app);
                    dropDownPreference.setVisible(false);
                    dialog.dismiss();
                })
                .setNegativeButton("关闭", (dialog, which) -> dialog.dismiss())
                .setNeutralButton("启动应用", ((dialog, which) -> SoftwareManager.getInstance().openApplication(requireActivity(), requireContext(), app.getPackageName(), app.getClazzName())))
                .setCancelable(false)
                .create();
        alertDialog.show();
    }
}
